export default {
  data() {
    return {
      radioValKey: '_typeColumn_radioVal',
      radioIdKey: '_typeColumn_radioId',
      radioOriginDataKey: '_typeColumn_radioOriginData'
    }
  },
  watch: {
    data: {
      immediate: true,
      deep: true,
      handler() {
        this.setRadioColData(this.data)
      }
    },
    // 表格是否挂在完成
    tableIsInit: {
      deep: true,
      immediate: true,
      handler(init) {
        if (!init.value) { return }
        if (this.busEvent) {
          // 设置 radio 事件 冒泡
          this.busEvent.value.on('radio-change', (row, index) => {
            this.$emit('radio-change', row, index)
          })
          this.busEvent.value.on('radio-click', (row, index) => {
            this.$emit('radio-click', row, index)
          })
        }
      }
    }
  },
  methods: {
    // 设置 radio 默认选中项 - 参考 el-table selection Api
    toggleRowRadio(row, checked) {
      this.busEvent.value.$emit('toggleRowRadio', row, checked)
    },
    // 清除 radio 默认选中项
    clearRadio() {
      this.busEvent.value.$emit('clearRadio', ...arguments)
    },
    // 创建内置 radioData
    setRadioColData(originData = this.data) {
      if (!originData?.length) {
        return
      }
      // 创建内置 radioData
      // 公用数据源
      const deepData = [...originData]
      if (deepData.length) {
        const { radioValKey, radioIdKey, radioOriginDataKey } = this
        this.setDataLeveKey(deepData, (dataItem, index, leve) => {
          // 第一层数据
          // 不对深层做处理
          if (leve === 0) {
            const originDataItem = originData[ index ]
            if (!(radioIdKey in dataItem)) {
              dataItem[ radioIdKey ] = Math.random().toString().slice(2)
              // 挂在原数据
              dataItem[ radioOriginDataKey ] = originDataItem
            }
            if (!(radioValKey in dataItem)) {
              const radioVal = this.getRadioValOfOriginDataHasChcked(originDataItem)
              dataItem[radioValKey] = radioVal
            }
          }
          return dataItem
        })
      }
    },
    // 对比原数据item 与 选中 row 判断checked val
    getRadioValOfOriginDataHasChcked(originData, diffData = this.radioCheckedData) {
      if (!originData) {
        throw Error('Arg: originData is not defined')
      }
      if (!diffData) {
        return false
      }
      return originData === diffData
    },
    // data 自迭代设置属性
    setDataLeveKey(data, leveFun, leve = 0, childrenKey = 'children') {
      if (data?.length) {
        data.forEach((dataItem, dataItemIndex) => {
          if (leveFun) {
            dataItem = leveFun(dataItem, dataItemIndex, leve)
          }
          if (childrenKey in dataItem) {
            this.setDataLeveKey(dataItem[ childrenKey ], leveFun, leve + 1)
          }
        })
      }
      return data
    }
  }
}
